package com.woniuxy.redis01.service;

import com.woniuxy.redis01.entity.Stu;
import com.woniuxy.redis01.mapper.StuMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author author
 * @Create 2023-10-30 14:37
 */
@Service
public class GoodService {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    StuMapper stuMapper;

    public void init() {
        ListOperations<String, Object> opsForList =redisTemplate.opsForList();
        for(int i=1;i<=1000;i++){
            opsForList.leftPush("list", i);
        }
    }

    public void second(){
        //一人一单
        //先去redis判断redis是否存在
        //数据库查询当前用户是否下过订单
        ListOperations<String, Object> opsForList =redisTemplate.opsForList();
        Object sid = opsForList.rightPop("list");
        if(sid !=null){
            //抢购成功，redis存储信息    key--uid/uname  value--商品id
            System.out.println("秒杀成功");
            //抢购成功，添加订单
            Stu stu=new Stu(Integer.parseInt(sid.toString()),"xxx",1);
            System.out.println("发送消息，产生订单的时间:"+new Date());
//            stuMapper.insertStu(stu);
            //使用消息队列，解耦，限流
            rabbitTemplate.convertSendAndReceive("exchangeorder", "dead.order", stu);
        }else{
            System.out.println("秒杀结束，感谢参与");
        }
    }
}
